<template>
  <div class="student-distribution">
    <div class="chart-container" ref="chartContainer"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'StudentDistributionChart',
  data() {
    return {
      chart: null,
      distributionData: []
    }
  },
  methods: {
    async fetchData(examId) {
      try {
        const response = await this.axios.get(`/api/school-work/student-distribution/${examId}`);
        this.distributionData = response.data;
        this.initChart();
      } catch (error) {
        console.error('获取学生分布数据失败:', error);
        this.$message.error('获取数据失败');
      }
    },
    initChart() {
      if (!this.chart) {
        this.chart = echarts.init(this.$refs.chartContainer);
      }
      
      // 处理数据
      const classes = [...new Set(this.distributionData.map(item => item.className))];
      const subjects = [...new Set(this.distributionData.map(item => item.subject))];
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['学优生', '学困生']
        },
        xAxis: [
          {
            type: 'category',
            data: classes,
            axisLabel: {
              interval: 0,
              rotate: 30
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '人数'
          }
        ],
        series: subjects.map(subject => [
          {
            name: `${subject}-学优生`,
            type: 'bar',
            stack: subject,
            data: this.distributionData
              .filter(item => item.subject === subject)
              .map(item => item.excellentCount)
          },
          {
            name: `${subject}-学困生`,
            type: 'bar',
            stack: subject,
            data: this.distributionData
              .filter(item => item.subject === subject)
              .map(item => item.poorCount)
          }
        ]).flat()
      };
      
      this.chart.setOption(option);
    }
  },
  mounted() {
    const examId = this.$route.params.examId;
    this.fetchData(examId);
    
    // 监听窗口大小变化，调整图表大小
    window.addEventListener('resize', () => {
      this.chart && this.chart.resize();
    });
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
    
    window.removeEventListener('resize', this.chart.resize);
  }
}
</script>

<style scoped>
.student-distribution {
  margin: 20px;
}
.chart-container {
  width: 100%;
  height: 400px;
}
</style> 